package com.etoak.web.login.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etoak.jwt.JwtUtils;
import com.etoak.utils.ResultUtils;
import com.etoak.utils.ResultVo;
import com.etoak.web.login.entity.Login;
import com.etoak.web.login.entity.LoginVo;
import com.etoak.web.login.service.LoginService;
import com.etoak.web.sys_user.entity.SysUser;
import com.etoak.web.sys_user.service.SysUserService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author by 孙有泽
 * @Date 2025/2/21 17:04
 * @Description
 */
@RestController
@RequestMapping("/api/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private AuthenticationManager authenticationManagerBean;

    @GetMapping("/getImage")
    public ResultVo getImage(HttpServletRequest request){
        HttpSession session = request.getSession();
        String text = defaultKaptcha.createText();
        session.setAttribute("code",text);
        BufferedImage image = defaultKaptcha.createImage(text);
        ByteArrayOutputStream outputStream=null;
        try{
            outputStream=  new ByteArrayOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            BASE64Encoder decoder=new BASE64Encoder();
            String encode = decoder.encode(outputStream.toByteArray());
            String captchBase64="data:image/jpeg;base64,"+encode.replace("\r\n","");
            return ResultUtils.success(200,"生成成功",captchBase64);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return ResultUtils.error("生成失败");
    }

    @PostMapping()
    public ResponseEntity<ResultVo> login(@RequestBody Login login, HttpServletRequest request) {
        // 获取用户输入的验证码
        String code = login.getCode();
        System.out.println("User input code: " + code);

        // 从session中获取存储的验证码
        HttpSession session = request.getSession();
        String codeFromSession = (String) session.getAttribute("code");
        System.out.println("Code from session: " + codeFromSession);

        // 验证码校验
        if (code == null || !code.equals(codeFromSession)) {
            return new ResponseEntity<>(ResultUtils.error("验证码错误"), HttpStatus.BAD_REQUEST);
        }
        String encode = bCryptPasswordEncoder.encode(login.getPassword());
        System.out.println(encode);
        // 创建认证令牌
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword());
        System.out.println(usernamePasswordAuthenticationToken+"343242");
            // 认证用户
            Authentication authenticate = authenticationManagerBean.authenticate(usernamePasswordAuthenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authenticate);

            // 获取认证成功的用户信息
            SysUser sysUser = (SysUser) authenticate.getPrincipal();

            // 准备JWT payload
            Map<String, String> payload = new HashMap<>();
            payload.put("id", sysUser.getId());
            payload.put("username", sysUser.getUsername());
            // 生成JWT token
            String token = jwtUtils.generateToken(payload);
            // 构建响应对象
            LoginVo loginVo = new LoginVo();
            loginVo.setToken(token);
            loginVo.setNickname(sysUser.getNickname());
            loginVo.setId(sysUser.getId());
            return new ResponseEntity<>(ResultUtils.success("登录成功", loginVo), HttpStatus.OK);
        }

        @PostMapping("/loginOut")
        public ResultVo loginOut(HttpServletRequest request, HttpServletResponse response){
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null) {
                new SecurityContextLogoutHandler().logout(request, response, authentication);
            }
            return ResultUtils.success("退出成功");

        }
}
